package com.menchao.carsales.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.swing.*;
import java.util.Date;

/**
 * Porject: carsales
 * Date: 2021/7/22
 * Author: menchao
 * Description: JWT工具类
 */

public class JwtUtils {

    public static void main(String[] args) {

        String token = sign("张三","123456");
        System.out.println("token: " + token);

        boolean isToken = verifyToken(token,"张三","123456");
        System.out.println("isToken: " + isToken);

        String userName = getUserName(token);
        System.out.println("userName: " + userName);



        System.out.println();

    }

    //token过期时间30分钟
    public static final long EXPIRE_TIME = 30 * 60 * 1000;


    /**
     * 生成签名
     * @param userName 用户名（一般是唯一标识）
     * @param secret 密钥
     * @return
     */
    public static String sign(String userName,String secret){
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create().withClaim("username", userName).withExpiresAt(date).sign(algorithm);
    }

    /**
     * 获得token中的用户信息
     * @param token
     * @return
     */
    public static String getUserName(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 校验token是否正确
     * @param token
     * @param username
     * @param secret
     * @return
     */
    public static boolean verifyToken(String token, String username, String secret){
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

}
